package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.demo.common.R;
import com.example.demo.dto.LoginUser;
import com.example.demo.dto.UserDto;
import com.example.demo.entity.User;
import com.example.demo.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Slf4j
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<UserDto> login(@RequestBody User user) {
        //记录日志
        log.info("登录user{}", user);
        UserDto login = loginService.login(user);
        if (login.equals(null)) {
            return R.error("账号或密码错误");
        }
        return R.success(login);
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public R<String> register(@RequestBody User user) {
        //记录日志
        log.info("注册user{}", user);
        boolean register = loginService.register(user);
        if (!register) {
            return R.error("已存在用户,请登录");
        }
        return R.success("注册成功");
    }

    /**
     * 退出
     *
     * @param request
     * @return
     */
    @RequestMapping("/loginOut")
    public R<String> logout() {
        log.info("退出user{}");
        loginService.logout();
        return R.success("已退出");
    }

}
